package com.withoutwords.ui;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.android.gcm.GCMRegistrar;
import com.withoutwords.engine.BitmapCache;
import com.withoutwords.engine.Common;
import com.withoutwords.engine.Game;
import com.withoutwords.engine.GameController;
import com.withoutwords.engine.MyInfo;
import com.withoutwords.engine.comminication.CommunicationManager;
import com.withoutwords.engine.comminication.IServerResultListener;
import com.withoutwords.engine.comminication.ServerRequests;
import com.withoutwords.engine.settings.Settings;
import com.withoutwords.engine.social.ISocialNetworkController;
import com.withoutwords.engine.social.SocialEngine;
import com.withoutwords.engine.social.SocialNetwork;
import com.withoutwords.engine.social.SocialUser;
import com.withoutwords.engine.social.listeners.ISocialFriendListListener;
import com.withoutwords.ui.custom.GamesExpandableListAdapter;
import com.withoutwords.ui.custom.MyCustomButton;
import com.withoutwords.ui.custom.MyCustomTextView;
import com.withoutwords.GCMIntentService;
import com.withoutwords.R;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ExpandableListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class WithoutWordsActivity extends BaseActivity implements
		OnClickListener, IServerResultListener, ISocialFriendListListener {

	GamesExpandableListAdapter friendsGamesListAdapter;
	GamesExpandableListAdapter openedGamesListAdapter;
	CommunicationManager CommMgrInstance;
	ISocialNetworkController fbController;
	Handler uihandler;
	ProgressBar pFriendsBarWait;
	ProgressBar pOpenedBarWait;
	Handler joinGameHandler;
	Handler openGameHandler;

	ArrayList<SocialUser> socialFriends;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		

		pFriendsBarWait = (ProgressBar) findViewById(R.id.progressBarFriends);
		pOpenedBarWait = (ProgressBar) findViewById(R.id.progressBarOpened);
		// getApplication().setTheme(resid)
		try {
			// push notification init
			GCMRegistrar.checkDevice(this.getApplicationContext());
			GCMRegistrar.checkManifest(this.getApplicationContext());
			final String regId = GCMRegistrar.getRegistrationId(this);
			if (regId.equals("")) {
				GCMRegistrar.register(this.getApplicationContext(),
						GCMIntentService.SenderID);
			} else {
				Settings.getInstance().setPushToken(regId);
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		CommMgrInstance = CommunicationManager.getCommnuicationManager();
		boolean bConnAvailble = CommMgrInstance
				.isConnectionAvailable(getApplicationContext());

		if (!bConnAvailble) {
			Toast.makeText(WithoutWordsActivity.this,
					getString(R.string.error_con_start), Toast.LENGTH_LONG)
					.show();
		}

		// check if user is logged in
		if (!SocialEngine.getSocialEngine().isLoggenIn(this)) {
			startLoginActivity();
		}

		// ui init
		MyCustomButton btn = (MyCustomButton) findViewById(R.id.btnInvite);
		btn.setOnClickListener(this);

		btn = (MyCustomButton) findViewById(R.id.btnCreateGame);
		btn.setOnClickListener(this);

		// ////////////////////////////////////////////////

		GameController.getInstance().loadOpenedGames();
		
		ExpandableListView exList = (ExpandableListView) findViewById(R.id.lstFriendsGames);
		if(exList != null )
		{

			
		exList.setEmptyView(findViewById(R.id.empty_friends));
		}
		
		// /initialize handlers
		uihandler = new Handler();
		joinGameHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {

				super.handleMessage(msg);
				Bundle data = msg.getData();
				Game game = (Game) data.get("game");
				Intent intent = new Intent(WithoutWordsActivity.this,
						ViewerPlayingActivity.class);
				intent.putExtra(Common.gameJoined, false);
				intent.putExtra("game", game);
				// GameController.getInstance().joinGame(game);
				startActivity(intent);

				// finish();
			}
		};
		openGameHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {

				super.handleMessage(msg);
				Bundle data = msg.getData();
				Game game = (Game) data.get("game");
				MyInfo me = Settings.getInstance().getMyInfo();
				if (me != null && game != null ) {
					{
						String socialId = game.getGameOwner()
								.getSocialID();
						if (socialId != null &&
								socialId.equalsIgnoreCase(
										me.getSocialUser().getSocialID())) {
							Intent intent = new Intent(
									WithoutWordsActivity.this,
									ActorPlayingActivity.class);
							
							intent.putExtra("game", game);
							startActivity(intent);
							
						} else {
							Intent intent = new Intent(
									WithoutWordsActivity.this,
									ViewerPlayingActivity.class);
							intent.putExtra(Common.gameJoined, true);
							intent.putExtra("game", game);
							startActivity(intent);

						}
					}
				}
				
			
			}
		};

		playSound(soundResId);
	}

	@Override
	protected void setBitmaps() {
		// TODO Auto-generated method stub
		super.setBitmaps();
		setLayoutBitmap(R.id.lyBlackboard, R.drawable.blackboard);

	}

	@Override
	protected void unsetBitmaps() {
		// TODO Auto-generated method stub
		super.unsetBitmaps();
		unsetLayoutBitmaps(R.id.lyBlackboard);

	}

	
	@Override
	protected void releaseBitmaps() {

		super.releaseBitmaps();
		/*
		 * BitmapCache .getCacheInstance().deleteDrawable(R.drawable.intro);
		 */
		BitmapCache.getCacheInstance().deleteDrawable(R.drawable.blackboard);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnInvite: {
			ISocialNetworkController fbController = SocialEngine
					.getSocialEngine().getSocialNetworkController(
							SocialNetwork.Facebook);
			fbController.inviteFriends(this, getString(R.string.facebook_invite_message));
			break;
		}
		case R.id.btnCreateGame: {
		/*	if (GameController.getInstance().isPendingGameExist()) {

				DialogInterface.OnClickListener positiveLisenter = new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						GameController.getInstance().leaveGame();
						startActivity(new Intent(getApplicationContext(),
								CreateGameActivity.class));
					}
				};

				Common.showLeaveDialog(this, positiveLisenter, null);

			} else {
*/
				startActivity(new Intent(getApplicationContext(),
						CreateGameActivity.class));
			//}
			break;
		}
		}
	}

	void setOpenedGames(ArrayList<Game> gamesArr)
	{
		if(openedGamesListAdapter == null)
		{
		openedGamesListAdapter = new GamesExpandableListAdapter(
				WithoutWordsActivity.this, openGameHandler);
		ExpandableListView exList = (ExpandableListView) findViewById(R.id.lstMyGames);
		if(exList != null)
		{
		//	MyCustomTextView tv = new MyCustomTextView(this);
		//tv.setText("No games found");
		exList.setEmptyView( findViewById(R.id.empty_opened));
			exList.setAdapter(openedGamesListAdapter);
		}
		}
		openedGamesListAdapter.setGames( gamesArr);
		openedGamesListAdapter.notifyDataSetChanged();
		
		//exList.expandGroup(0);
	}
	@Override
	public void onRequestSucceed(ServerRequests serverRequest,
			final Bundle response) {
		switch (serverRequest) {
		case getUserGames: {
			uihandler.post(new Runnable() {

				@Override
				public void run() {
					if(pFriendsBarWait != null)
					{
					pFriendsBarWait.setVisibility(View.GONE);
					}
					// initialize empty list
					friendsGamesListAdapter = new GamesExpandableListAdapter(
							WithoutWordsActivity.this, joinGameHandler);
					Object ooo = response.getSerializable("games");
					ArrayList<Game> games = (ArrayList<Game>) ooo;
					games.removeAll(GameController.getInstance().getOpenedGames());
					friendsGamesListAdapter.setGames(games);
					ExpandableListView exList = (ExpandableListView) findViewById(R.id.lstFriendsGames);
					if(exList != null )
					{
						exList.setAdapter(friendsGamesListAdapter);
						exList.expandGroup(0);
					}
				}
			});
			break;
		}

		case getOpenedGames: {
			uihandler.post(new Runnable() {

				@Override
				public void run() {
					if(pOpenedBarWait != null)
					{
					pOpenedBarWait.setVisibility(View.GONE);
					}
					// initialize empty list
					ArrayList<Game> gamesArr = (ArrayList<Game>)response.getSerializable("games");
					for(Game game : gamesArr)
					{
						GameController.getInstance().addGame(game);
					}
					setOpenedGames(gamesArr);

				}
			});
			break;
		}

		default:
			break;
		}

	}

	@Override
	public void onRequestFailed(final ServerRequests serverRequest, final String error) {
		// TODO Auto-generated method stubpBarWait.setVisibility(View.GONE);

		uihandler.post(new Runnable() {

			@Override
			public void run() {
				if(serverRequest == ServerRequests.getOpenedGames)
				{
					pOpenedBarWait.setVisibility(View.GONE);
				}
				else if(serverRequest == ServerRequests.getUserGames)
				{
				pFriendsBarWait.setVisibility(View.GONE);
				}
				
				Toast.makeText(WithoutWordsActivity.this, error,
						Toast.LENGTH_LONG).show();

			}
		});

	}

	@Override
	public void onError(final String error) {

		uihandler.post(new Runnable() {

			@Override
			public void run() {
				//pFriendsBarWait.setVisibility(View.GONE);
				if(error != null && error.contains("OAuthException"))
				{
					SocialEngine.getSocialEngine().logout(WithoutWordsActivity.this);
					Settings.getInstance().setMyInfo(new MyInfo(), true);
					Toast.makeText(WithoutWordsActivity.this,
							getString(R.string.facebook_expired_error), Toast.LENGTH_LONG).show();
					startLoginActivity();

				}
				else
				{
				Toast.makeText(WithoutWordsActivity.this,
						getString(R.string.error_fb), Toast.LENGTH_LONG).show();

			}
			}
		});
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if (socialFriends == null || socialFriends.size() < 1) {
			fbController = SocialEngine.getSocialEngine()
					.getSocialNetworkController(SocialNetwork.Facebook);
			fbController.readFriendList(this, true);
		} else {
			getUserGames();
		}
		if (friendsGamesListAdapter != null) {
			pFriendsBarWait.setVisibility(View.VISIBLE);
			friendsGamesListAdapter.setGames(new ArrayList<Game>());
			friendsGamesListAdapter.notifyDataSetChanged();
		}
		
		
		//getOpenedGames();
		
			ArrayList<Game> games = GameController.getInstance().getOpenedGames();
			/*if(games == null ||  games.size() == 0 )
			{
				pOpenedBarWait.setVisibility(View.VISIBLE);
			}
			else */
			{
				pOpenedBarWait.setVisibility(View.GONE);
			}
			setOpenedGames(games);
		

	}

	private void getUserGames() {
		Bundle bundle = new Bundle();
		JSONArray arrayJson = new JSONArray();
		for (int i = 0; i < socialFriends.size(); i++) {
			try {
				arrayJson.put(i, socialFriends.get(i).toJSON());
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		JSONObject obj = new JSONObject();
		try {
			obj.put(Common.usersCode, arrayJson);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String objStr = obj.toString();
		bundle.putString(Common.usersCode, objStr);
		// read games
		CommMgrInstance = CommunicationManager.getCommnuicationManager();
		CommMgrInstance
				.request(this, ServerRequests.getUserGames, bundle, this);
	}
	private void getOpenedGames()
	{
		Bundle bundle = new Bundle();
		MyInfo me = Settings.getInstance().getMyInfo();
		if (me != null ) {
			bundle.putString(Common.userIdCode, me.getSocialUser().getSocialID());
			
	
		// read games
		CommMgrInstance = CommunicationManager.getCommnuicationManager();
		CommMgrInstance
				.request(this, ServerRequests.getOpenedGames, bundle, this);
		}
	}

	@Override
	public void onFriendListRecieved(ArrayList<SocialUser> friends) {

		socialFriends = friends;
		getUserGames();
		// CommMgrInstance.request(ServerRequests.getPlayingUser, bundle, this);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// MenuItem item1 = Menu.
		menu.add(getString(R.string.settings));
		menu.add(getString(R.string.help));
		menu.add(getString(R.string.feedback));
		// TODO Auto-generated method stub
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		
		if (item.getTitle().equals(getString(R.string.settings))) {

				startActivityForResult(new Intent(this,SettingsActvity.class),SettingsActvity.RequestCode);
			
			
		} else if (item.getTitle().equals(getString(R.string.help))) {
			/*String urlPath = "";
			urlPath = getString(R.string.help_url);
			Uri uri = Uri.parse(urlPath);
			if (uri != null)
				startActivity(new Intent(Intent.ACTION_VIEW, uri));*/
			Intent intent = new Intent(this,LoginActivity.class);
			intent.putExtra(Common.openHelp, true);
			startActivity(intent);
		}
		else if (item.getTitle().equals(getString(R.string.feedback))) {
			String urlPath = "";
			urlPath = getString(R.string.feedbackURL);
			Uri uri = Uri.parse(urlPath);
			if (uri != null)
				startActivity(new Intent(Intent.ACTION_VIEW, uri));
		}
		
		// TODO Auto-generated method stub
		return super.onOptionsItemSelected(item);
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode == SettingsActvity.RequestCode)
		{
			if(resultCode == SettingsActvity.ResultLoggedOut)
			{
				startLoginActivity();
			}
		}
	}
	void startLoginActivity()
	{
		startActivity(new Intent(getApplicationContext(),
				LoginActivity.class));
		finish();
	}
	
	@Override
	public void finish() {
		GameController.getInstance().saveOpenedGames();
		super.finish();
	}
}
